<?php

class InvitesController extends AppController {

	var $components = array('SwiftMailer');
	
	var $helpers = array('Html','Text','Javascript','Ajax');

	function send() {
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_ADMIN)) {
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		if (empty($this->data)) {
			//print_r($_SERVER);
		} else {
			if ($this->Invite->save($this->data)) {
				$text = "http://" . $_SERVER['HTTP_HOST'] . str_replace('/index.php', '', $_SERVER['PHP_SELF']) . '/invites/respond/' . $this->Invite->getLastInsertId();
				$to['Member'] = $this->data['Invite'];
				
				if($this->SwiftMailer->connect()) {
					$this->SwiftMailer->addTo('to',$to['Member']['email_address'],$to['Member']['first_name'] . ' ' . $to['Member']['last_name']);
					$this->SwiftMailer->addTo('bcc','help@westmichigancoop.com','Invite Duplicate');
					$this->SwiftMailer->addTo('from',"invites@westmichigancoop.com","WMCoop Invitation");
					$this->set('swiftMailer_data',$text);
					
					if(!$this->SwiftMailer->sendView("West Michigan Coop Invitation",'invite','plain')) {
						echo "The mailer failed to Send. Errors:";
						pr($this->SwiftMailer->errors());		
					}
				} else {
					echo "The mailer failed to connect. Errors:";
					pr($this->SwiftMailer->errors());
				}
				
				$this->redirect('/members/menu');
			} else {
				$this->set('errorMessage','There is an error in your form:');
			}
		}
		$this->render();
	}
	
	function respond($id = null) {
		if ($id === null) {//if there's no id, they can't respond to an invite.
			$this->Session->setFlash("That operation is not available to you.");
			$this->redirect('/');
		} else {
			$invite = $this->Invite->find("id = " . $id);
			if (empty($invite)) {
				$this->Session->setFlash("That invitation has already been responded to.");
				$this->redirect('/');
			} else {
				//display the form
				//print_r($invite);
				$this->data['Member'] = $invite['Invite'];
				$this->set('invite_id',$id);
				//$this->render();
			}
		}
	}
	
	function taken($id = null) {
		if ($id === null) {
			$this->Session->setFlash("That operation is not available to you.");
			$this->redirect('/');
		} else {
			$this->Invite->del($id);
			$this->render();
		}
	}
	
}
